<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/5/24
 * Time: 9:25
 * Mail:87658989@qq.com
 */

namespace app\adminapi\model;
use app\base\exception\RecordNotFoundException;
use app\base\service\Beidou;
use think\exception\DbException;
use think\Db;
use think\Hook;
use app\adminapi\filter;
use traits\model\SoftDelete;

class Order extends Common
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    /**
     * 订单列表
     * @param string $field
     * @param array $where
     * @param int $page
     * @param int $num
     * @return array
     */
    public function orderList($field='*',$where=[],$page=1,$num=10){
        $filter          = new filter\OrderList();
        $filter->analyzeField();
        list(,$msg) = $filter->checkField($field);
        list(,$whereMsg) = $filter->checkWhere($where);
        $data['note'] = "查询条件json输入格式如{'order_state':['in','6,7,8,9,10,11,12'],'passenger_name':['like','%王%']}";

        $buildQuery = function($query) use ($whereMsg) {
            self::authCompanyQuery($query, $whereMsg, 'a.company_id');
        };

        try{
            $data['data'] = $this->alias('a')
                ->join('order_gps b','a.order_id = b.order_id','left')
                ->join('order_fee c','a.order_id = c.order_id','left')
                ->join('car_type e','a.car_type_id = e.car_type_id','left')
                ->join('car_type f','a.dispatch_car_type_id = f.car_type_id','left')
                ->join('company d','a.company_id = d.company_id','left')
                ->join('driver g','a.driver_id = g.driver_id','left')
                ->join('car h','a.car_id = h.car_id','left')
                ->field($msg)
                ->where($buildQuery)
                ->page($page,$num)
                ->order('a.order_id desc')
                ->select();
        }catch (DbException $e){
            return [0,$e->getMessage()];
        }
        $data['count'] = $this->alias('a')
            ->join('order_gps b','a.order_id = b.order_id','left')
            ->join('order_fee c','a.order_id = c.order_id','left')
            ->join('car_type e','a.car_type_id = e.car_type_id','left')
            ->join('car_type f','a.dispatch_car_type_id = f.car_type_id','left')
            ->join('company d','a.company_id = d.company_id','left')
            ->join('driver g','a.driver_id = g.driver_id','left')
            ->join('car h','a.car_id = h.car_id','left')
            ->where($buildQuery)
            ->count();
        $data['description'] = $filter->title;
        $data['fields']      = $filter->fieldTitle;
        return [1,$data];
    }

    /**
     * 获取报价订单
     * @param string $status
     * @param int $oid
     * @param int $page
     * @param int $num
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getBusOrder($status='21',$oid=0,$page=1,$num=10){
        $where['order_state'] = ['in',$status];
        $oid >0 && $where['a.order_id'] = $oid;
        $fields = 'a.order_id,b.plan_time,a.booking_type,a.passenger_num,a.car_num,a.order_state,c.start_fee';
        $fields.= ',a.apply_time,d.price_time,d.link_man,d.link_phone,d.price,a.car_num,d.total_amount,d.car_data';
        $fields.= ',b.from_addr,b.to_addr,a.order_time,a.order_no,a.passenger_name,a.orderer,a.use_explain,a.use_type';
        $fields.= ',a.passenger_id,a.is_return,e.type,e.car_type,a.order_type';

        $buildQuery = function($query) use ($where) {
            self::authCompanyQuery($query, $where, 'a.company_id');
        };

        try{
            $orders = $this->alias('a')
                ->join('order_gps b','a.order_id = b.order_id','left')
                ->join('order_fee c','a.order_id = c.order_id','left')
                ->join('order_bus d','a.order_id = d.order_id','left')
                ->join('car_type e','a.car_type_id = e.car_type_id','left')
                ->where($buildQuery)
                ->field($fields)
                ->page($page,$num)
                ->order('a.order_id desc')
                ->select();
        }catch (DbException $e){
            $orders = [];
        }
        return $orders;
    }

    /**
     * 后台报价
     * @param array $data
     * @return array
     */
    public function setBusPrice($data=[]){
        // 启动事物管理
        Db::startTrans();
        try {
            $where = [
                'order_id' => $data['order_id'],
                'order_state' => ['IN', [21, 22, 23]]
            ];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'a.company_id');
            };

            $ret = Db::name('order')
                ->where($buildQuery)
                ->update(['order_state'=>23]);
            if($ret==0){
                return [0,'订单状态不对'];
            }
            $data['price_time'] = date('Y-m-d H:i:s');
            Db::name('order_bus')->insert($data);
            // 更新订单费用
            $fee = $data['total_amount'];
            $feeData['pre_fee']  = $fee;
            $feeData['start_fee']= $fee;
            $feeData['passenger_money'] = $fee;
            $feeData['company_money']   = $fee;
            $feeData['order_money']     = $fee;
            Db::name('order_fee')->where('order_id',$data['order_id'])->update($feeData);
            Db::commit();
            Hook::listen('price_order',$data['order_id']);
            return [1,'ok'];
        } catch (\Exception $e) {
            Db::rollback();
            return [0,$e->getMessage()];
        }
    }

    /**
     * 获取订单北斗记录
     * @param int $oid
     * @return mixed
     * @throws DbException
     * @throws RecordNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderBeidouTrack($oid=0){
        $where = [
            'a.order_id' => $oid,
        ];
        $buildQuery = function($query) use ($where) {
            self::authCompanyQuery($query, $where, 'a.company_id');
        };

        $order = $this->alias('a')
            ->join('order_gps b','a.order_id = b.order_id','left')
            ->where($buildQuery)
            ->find();
        if(empty($order)) throw new RecordNotFoundException('订单不存在');
        $data['data'] = (new Beidou())->getTrack($order['car_number'],strtotime($order['go_time']),strtotime($order['arrival_time']));
        return $data;
    }

    /**
     * 给订单添加异常备注
     * @param $params
     * @return false|int
     * @throws DbException
     * @throws RecordNotFoundException
     */
    public function remark($params) {
        $where = ['order_id' => $params['order_id']];
        $buildQuery = function($query) use ($where) {
            self::authCompanyQuery($query, $where, 'company_id');
        };

        $order = self::get($buildQuery);
        if(!$order) {
            throw new RecordNotFoundException();
        }

        return $this->isUpdate(true)->save($params);
    }
}